/**
 * Created by yeso on 2015/9/24.
 */
angular.module('app.auth', [
    'ngCookies'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('login', {
            url: "/login",
            templateUrl: "tpls/auth/login.html",
            controller: 'LoginController'
        })
        .state('home.manager', {
            url: '/manager',
            views: {
                'main@home': {
                    templateUrl: "tpls/manager/insertManager.html",
                    controller: 'NewManagerController'
                }
            }
        })
        .state('home.detail', {
            url: '/managerdetail',
            views: {
                'main@home': {
                    templateUrl: "tpls/manager/managerDetail.html",
                    controller: 'ManagerDetailController'
                }
            }
        })
}])

//管理员登录

.controller('LoginController', ['$scope','$state','$cookieStore','LoginService', function($scope, $state, $cookieStore, LoginService) {
    $scope.manage = {};
    $scope.loginmanager = function (manager) {
        //$q $http ==  //$resource
        var promise = LoginService.login(manager).$promise; // 同步调用，获得承诺接口
        promise.then(function (data) { // 调用承诺API获取数据 .resolve
            $cookieStore.put("manager_cookie", data);
            //console.log("cookie was set");
            $state.go('home.shoplist');
        }, function (data) {  // 处理错误 .reject
            alert("Username or Password error");
        });
    }
}])

//新增管理员

.controller('NewManagerController', ['$scope','$state','LoginService', function($scope, $state, LoginService) {
    $scope.manager = {};
    $scope.registmanager = function (manager) {
        var registresult = LoginService.register(manager).$promise;
        registresult.then(function (data) { //处理.resolve
            if (data == 1) {
                alert('Add manager is success');
                $state.go('index');
            } else {
                alert('the manager is exits');
                $scope.manager = {};
            }
        }, function (data) { //处理。reject
            alert("the service is error");
        });
    }
}])

//判断cookie

.controller('ManagerDetailController', ['$scope','$state','$cookieStore','LoginService', function($scope, $state, $cookieStore, LoginService) {
    var data = $cookieStore.get('manager_cookie');
    if (data == undefined) {
        alert("Page has expired, please login again");
        $state.go('login');
    } else {
        $scope.manager_cookie = data;
        //console.log("this is" + data.managername);
    }
}])

;
